#include "histogram_stretching.h"

#include "../histogram.h"

HistogramStretching::HistogramStretching(PNM* img) :
    Transformation(img)
{
}

HistogramStretching::HistogramStretching(PNM* img, ImageViewer* iv) :
    Transformation(img, iv)
{
}

PNM* HistogramStretching::transform()
{
    int width  = image->width();
    int height = image->height();

    PNM* newImage = new PNM(width, height, image->format());

	int min_R = 0;
	int min_G = 0;
	int min_B = 0;
	int min_L = 0;

	int max_R = 255;
	int max_G = 255;
	int max_B = 255;
	int max_L = 255;

	auto r_hist = image->getHistogram()->get(Histogram::RChannel);
	auto g_hist = image->getHistogram()->get(Histogram::GChannel);
	auto b_hist = image->getHistogram()->get(Histogram::BChannel);
	auto l_hist = image->getHistogram()->get(Histogram::LChannel);

	for(int i = 1; i < 255; i++)
	{
		if(min_R == 0 && r_hist->value(i) > 0) min_R = i;
		if(min_G == 0 && g_hist->value(i) > 0) min_G = i;
		if(min_B == 0 && b_hist->value(i) > 0) min_B = i;
		if(min_L == 0 && l_hist->value(i) > 0) min_L = i;

		if(r_hist->value(i) > 0) max_R = i;
		if(g_hist->value(i) > 0) max_G = i;
		if(b_hist->value(i) > 0) max_B = i;
		if(l_hist->value(i) > 0) max_L = i;
	}


	if (image->format() == QImage::Format_Indexed8)
    {
		for (int x=0; x<width; x++)
			for (int y=0; y<height; y++)
			{
				QRgb pixel = image->pixel(x,y);
				int newColor((255/(max_L-min_L))*(qGray(pixel)-min_L));				
				newImage->setPixel(x, y, newColor);
			}
    }
    else //if (image->format() == QImage::Format_RGB32)
    {
		for (int x=0; x<width; x++)
			for (int y=0; y<height; y++)
			{
				QRgb pixel = image->pixel(x,y);
				QColor newColor(
					(255/(max_R - min_R))*(qRed(pixel)-min_R),
					(255/(max_G - min_G))*(qGreen(pixel)-min_G),
					(255/(max_B - min_B))*(qBlue(pixel)-min_B)
				);
				
				newImage->setPixel(x,y,newColor.rgb());
			}
    }

    return newImage;
}


